package org.itboys.weixin.service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseService;
import org.itboys.mongodb.utils.page.Page;
import org.itboys.weixin.entity.WeixinConfig;
import org.itboys.weixin.entity.WeixinSendInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
 * 推送用的信息模板
 * @author weisky
 *
 * 2016年4月30日
 */
@Service
public class WeixinSendInfoService extends BaseService<WeixinSendInfo, Long>{
	
	private static final long serialVersionUID = 1L;
	
	@Resource(name="weixinDS")
	private MongoDataSource weixinSendInfoDataSource;
	@Autowired
	private WeixinConfigService weixinConfigService;

	@Override
	protected MongoDataSource getMongoDataSource() {
		return weixinSendInfoDataSource;
	}
	
	public WeixinSendInfo getByKey(String key){
		return super.getByField("key", key);
	}
	
	/**
	 * 新增或修改
	 * @param weixinSendInfo
	 * @return
	 */
	public boolean insert(WeixinSendInfo weixinSendInfo){
		try{
			if(weixinSendInfo.getId() != 0){//修改
				super.update(weixinSendInfo);
			}else{//新增
				boolean resu = super.exists("key", weixinSendInfo.getKey());
				if(resu){//key值是唯一的
					return false;
				}
				super.save(weixinSendInfo);
			}
			return true;
		}catch(Exception e){
			e.printStackTrace();
			logger.error("WeixinSendInfoService.insert error", e);
		}
		return false;
	}
	
	/**
	 * 组装带有微信名称信息的消息
	 * @param request
	 * @return
	 */
	public Page<WeixinSendInfo> listByPage(HttpServletRequest request){
		Page<WeixinSendInfo>  page = super.pageQuery(request);
		if(page != null && page.getData() != null){
			page.getData().forEach(pg -> {
				WeixinConfig wc = weixinConfigService.getById(pg.getWeixinId());
				if(wc != null){
					pg.setWeixinName(wc.getName());
				}
			});
		}
		return page;
	}

}
